using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using Quiki.ExpressionParsers;

namespace Quiki.DocumentPostprocessors
{
    public class DocumentElementsMerger : IDocumentPostprocessor
    {
        public void PostProcessDocument(WikiDocument document)
        {
            LookForElementsToMerge(document.RootElement);
        }

        private static void LookForElementsToMerge(WikiTextElement parentElement)
        {
            for (int i = 0; i < parentElement.ChildElements.Count - 1; i++)
            {
                WikiTextElement child1 = parentElement.ChildElements[i];
                if (child1.ChildElements.Count > 0)
                {
                    LookForElementsToMerge(child1);
                    continue;
                }

                WikiTextElement child2 = parentElement.ChildElements[i+1];
                if (child2.ChildElements.Count > 0)
                    continue;

                if (child1.ElementType == WikiTextElementType.Pre
                    && child2.ElementType == WikiTextElementType.Pre)
                {
                    MergePreElements(child1, child2);
                    parentElement.ChildElements.RemoveAt(i+1);
                    i--;
                }
            }
        }

        [SuppressMessage("Microsoft.Globalization", "CA1309:UseOrdinalStringComparison", MessageId = "System.String.EndsWith(System.String,System.StringComparison)")]
        private static void MergePreElements(WikiTextElement element1, WikiTextElement element2)
        {
            StringBuilder s = new StringBuilder(element1.Text);
            if (false == element1.Text.EndsWith(Environment.NewLine, StringComparison.InvariantCulture))
                s.Append(Environment.NewLine);
            s.Append(element2.Text);
            if (false == s.ToString().EndsWith(Environment.NewLine, StringComparison.InvariantCulture))
                s.Append(Environment.NewLine);

            element1.Text = s.ToString();
        }
    }
}